package com.paic.egis.smts.msg.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.paic.egis.smts.common.dto.CommonConstant;
import com.paic.egis.smts.common.dto.UserDTO;
import com.paic.egis.smts.common.util.LoggerUtil;
import com.paic.egis.smts.common.util.SessionAttributeNames;
import com.paic.egis.smts.common.web.controller.BaseController;
import com.paic.egis.smts.common.web.form.BaseArrayForm;
import com.paic.egis.smts.common.web.form.CommonBaseForm;
import com.paic.egis.smts.msg.dto.DeviceTokenDTO;
import com.paic.egis.smts.msg.dto.MsgLetterBoxDTO;
import com.paic.egis.smts.msg.dto.MsgPushDTO;
import com.paic.egis.smts.msg.service.ConfigSupportedMsgService;
import com.paic.egis.smts.msg.service.DeviceTokenService;
import com.paic.egis.smts.msg.service.MsgService;
import com.paic.egis.smts.msg.web.form.DeviceTokenForm;
import com.paic.egis.smts.msg.web.form.MessageRedirectForm;
import com.paic.pafa.appclient.annotation.BizServicesProxy;
import com.paic.pafa.exceptions.BusinessException;
import com.paic.pafa.web.session.SessionAttr;

@Controller
@RequestMapping("/message")
public class MsgController extends BaseController {
	
	@BizServicesProxy(beanName="configSupportedMsgService")
	private ConfigSupportedMsgService ConfigSupportedMsgService;

	@BizServicesProxy(beanName="msgService")
	private MsgService msgService;

	@BizServicesProxy(beanName="deviceTokenService")
	private DeviceTokenService deviceTokenService;

	/**
	 * 手机设备号入库
	 * 
	 * @param deviceForm
	 * @return
	 */
	@RequestMapping(value="/deviceTokenSave")
	public CommonBaseForm deviceTokenSave(@ModelAttribute DeviceTokenForm deviceForm) {
		CommonBaseForm result = new CommonBaseForm();
		DeviceTokenDTO dto = new DeviceTokenDTO();
		BeanUtils.copyProperties(deviceForm, dto);
		dto.setMessagecCount("0");
		try {
			deviceTokenService.saveDeviceToken(dto);
			return result;
		} catch (BusinessException e) {
			LoggerUtil.logError(this.getClass().getName(), "deviceTokenSave", e);
			result.setFailForm(e.getMessage());
			return result;
		}
	}

	/**
	 * 删除设备信息
	 * 
	 * @param deviceForm
	 * @return
	 */
	@RequestMapping(value = {"/deviceTokenColse",  "/deviceTokenClose"})
	public CommonBaseForm deviceTokenClose(@ModelAttribute DeviceTokenForm deviceForm) {
		CommonBaseForm form = new CommonBaseForm();
		try {
			DeviceTokenDTO dto = new DeviceTokenDTO();
			BeanUtils.copyProperties(deviceForm, dto);
			deviceTokenService.deleteDeviceToken(dto);
			return form;
		} catch (BusinessException e) {
			LoggerUtil.logError(this.getClass().getName(), "deviceTokenClose", e);
			form.setFailForm(e.getMessage());
			return form;
		}
	}

	/**
	 * 小信箱消息列表查询 
	 * 1. cssp 统一推送 
	 * 2. 第三方消息
	 * 3. 业务逻辑推送消息
	 * 
	 * @param deviceToken
	 * @param userId
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/letterBoxMessage", method=RequestMethod.GET)
	public CommonBaseForm queryLetterBoxMessage(@SessionAttr(value=SessionAttributeNames.SMTS_USER) UserDTO user,
			@RequestParam(value="productNotice", required=false)String productNotice,
			@RequestParam(value="systemNotice", required=false)String systemNotice,
			@RequestParam(value="deviceToken", required=true) String deviceToken) {
		BaseArrayForm form = new BaseArrayForm();
		// 设备号为空，直接返回
		try {
			// letter表中数据查询（包括业务消息和第三方消息推送）
			Map<String, String> reqMap = new HashMap<String, String>();
			reqMap.put("deviceToken", deviceToken);
			if(user != null && StringUtils.isNotBlank(user.getInputOrgIdentify())){
				LoggerUtil.trace(this.getClass().getName(), "letterBoxMessage", "InputOrgIdentify====" + JSONObject.toJSONString(user.getInputOrgIdentify()));
				reqMap.put("orgIdentify", user.getInputOrgIdentify());
				
			}
			reqMap.put("userId", user.getUserId());
			if ("N".equals(productNotice))
				reqMap.put("proType", productNotice);
			if ("N".equals(systemNotice))
				reqMap.put("sysType", systemNotice);

			List<MsgLetterBoxDTO> letters = msgService.fetchLetterMsgs(reqMap);
			// cssp消息推送
			List<MsgLetterBoxDTO> csspLetters = ConfigSupportedMsgService.fetchLetterBoxCsspMsgs(reqMap);
            List<MsgLetterBoxDTO> resultMsgs = new ArrayList<MsgLetterBoxDTO>();
            if(letters != null ){
            	resultMsgs.addAll(letters);
            }
            if(csspLetters != null){
            	resultMsgs.addAll(csspLetters);
            }
			form.setResultList(resultMsgs);
			
		} catch (BusinessException e) {
			LoggerUtil.logError(this.getClass().getName(), "queryLetterBoxMessage", e);
			form.setFailForm(e.getMessage());
		}
		return form;
	}

	/**
	 * 安卓用户消息推送  
	 * 1. cssp 统一推送 
	 * 2. 第三方消息 
	 * 3. 业务逻辑推送消息
	 * 
	 * @param deviceToken
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/androidMessage", method=RequestMethod.GET)
	public CommonBaseForm queryAndroidMessage(@RequestParam(value="deviceToken", required=true) String deviceToken,
			@SessionAttr(value=SessionAttributeNames.SMTS_USER) UserDTO user) {
		
		BaseArrayForm form = new BaseArrayForm();
		try {
			// push表中数据查询（包括业务消息和第三方消息推送）
			Map<String, String> reqMap = new HashMap<String, String>();
			reqMap.put("deviceToken", deviceToken);
			reqMap.put("userId", user.getUserId());
			reqMap.put("orgIdentify", user.getInputOrgIdentify());
			List<MsgPushDTO> pushMsgs = msgService.fetchPushMsgs(reqMap);
			//  cssp消息推送    
			List<MsgPushDTO> pushCsspMsgs = msgService
					.fetchPushCsspMsgs(reqMap);
			List<MsgPushDTO> result = new ArrayList<MsgPushDTO>();
			if (null != pushMsgs) {
				result.addAll(pushMsgs);
			}
			if (null != pushCsspMsgs) {
				result.addAll(pushCsspMsgs);
			}
			form.setResultList(result);
		} catch (BusinessException e) {
			LoggerUtil.logError(this.getClass().getName(), "queryAndroidMessage", e);
			form.setFailForm(e.getMessage());
		}
		return form;
	}

	/**
	 * 判断session是否过期
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/sessionOutOfDateJudge", method = RequestMethod.GET)
	public CommonBaseForm sessionOutOfDateJudge(
			@SessionAttr(value = SessionAttributeNames.SMTS_USER, required = false) UserDTO user) {
		CommonBaseForm form = new CommonBaseForm();
		if (user == null) {
			form.setReturnFlag(CommonConstant.ResponseStatus.TIMEOUT.status());
			form.setMsg(CommonConstant.ResponseStatus.TIMEOUT.msg());
		}
		return form;
	}

	@RequestMapping(value="/qmr.dox", method=RequestMethod.GET)
	public CommonBaseForm messageRedirect(HttpServletRequest request,
			HttpServletResponse response) {
		MessageRedirectForm form = new MessageRedirectForm();
		try {
			String id = request.getParameter("id");
			String messageRedirect = msgService.queryMessageRedirect(id);
			form.setMessageRedirect(messageRedirect);
		} catch (BusinessException e) {
			LoggerUtil.logError(this.getClass().getName(), "messageRedirect", e);
			form.setFailForm(e.getMessage());
		}
		return form;
	}

	@RequestMapping(value="/test.do", method=RequestMethod.GET)
	public CommonBaseForm test(@SessionAttr(value=SessionAttributeNames.SMTS_USER) UserDTO user) throws Exception {
		
		// 小信箱
		Map<String, String> reqMap = new HashMap<String, String>();
		reqMap.put("userId", user.getUserId());
		reqMap.put("proType", "N");
		List<MsgLetterBoxDTO> pushMsgs = msgService.fetchLetterMsgs(reqMap);
		System.out.println(pushMsgs);
		return null;
	}
	
}
